// pages/sharePost/sharePost.js
import {
  baseUrl
} from "../../utils/api.js";
var imageUtil = require('../../utils/img.js');
var imageheight1 = 0

const app = getApp()
var haveTap = 1
Page({

  /**
   * 页面的初始数据
   */
  data: {
    haveShare: 0, // 0：完成/未开始 1：分享
    CarteInfo: {},
    qrcodeUrl: "",
    bannerUrl: "",
    saveImgBtnHidden: false,
    openSettingBtnHidden: true,
    hidden_t: false,
    imagewidth1: 0, //缩放后的宽
    imageheight1: 0, //缩放后的高
  },
  imageLoad1: function (e) {
    var imageSize = imageUtil.imageUtil(e)
    var that = this
    var originalWidth = e.detail.width; //图片原始宽
    var originalHeight = e.detail.height; //图片原始高
    //图片高宽比
    var originalScale = originalHeight / originalWidth;
    console.log(originalScale)
    that.setData({
      imagewidth1: imageSize.imageWidth,
      imageheight1: imageSize.imageHeight,
    })
  },

  back_one() {
    wx.navigateBack({})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const CarteInfo = JSON.parse(decodeURIComponent(options.carte_info))
    CarteInfo.img.src = CarteInfo.img.src + '?x-oss-process=style/poster_image';
    CarteInfo.comLogo.src = CarteInfo.comLogo.src + '?x-oss-process=style/goods_skeletonize';

    this.setData({
      haveShare: 0,
      CarteInfo
    })
  },

  // 名片canvas渲染并打开分享遮罩层
  canvasAndShowshare: function () {
    const that = this
    const CarteInfo = this.data.CarteInfo
    //获取相册授权
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() { //这里是用户同意授权后的回调

              that.renderCanvasCarte(CarteInfo).then(render_canvas_res => {
                // console.log(render_canvas_res)
                wx.hideLoading()
                that.setData({
                  haveShare: 1
                })
              })
            },
            fail() { //这里是用户拒绝授权后的回调
              that.setData({
                saveImgBtnHidden: true,
                openSettingBtnHidden: false
              })
            }
          })
        } else { //用户已经授权过了
          that.renderCanvasCarte(CarteInfo).then(render_canvas_res => {
            // console.log(render_canvas_res)
            wx.hideLoading()
            that.setData({
              haveShare: 1
            })
          })
        }
      }
    })

  },
  handleSetting: function (e) {
    let that = this;
    // 对用户的设置进行判断，如果没有授权，即使用户返回到保存页面，显示的也是“去授权”按钮；同意授权之后才显示保存按钮
    if (!e.target.authSetting['scope.writePhotosAlbum']) {
      wx.showModal({
        title: '警告',
        content: '若不打开授权，则无法将图片保存在相册中！',
        showCancel: false
      })
      that.setData({
        saveImgBtnHidden: true,
        openSettingBtnHidden: false
      })
    } else {
      if (haveTap == 0) {
        console.log('屏蔽重复点击')
      } else {
        haveTap = 0
        wx.showModal({
          title: '提示',
          content: '您已授权，赶紧将图片保存在相册中吧！',
          showCancel: false
        })
        that.setData({
          saveImgBtnHidden: false,
          openSettingBtnHidden: true
        })
      }
    }
  },

  // canvas渲染
  renderCanvasCarte: function (params) {
    const that = this
    wx.showLoading({
      mask: 'true'
    })

    const wxGetImageInfo = function (src) {
      let p = new Promise((resolve, reject) => {
        console.log(src)
        wx.getImageInfo({
          src: src,
          success(res) {
            resolve(res)
            console.log('结果')
            console.log(res)
          },
          fail(err) {
            reject(err)
            console.log('结果')
            console.log(err)
          },
          complete() {

          }
        })
      })
      return p
    }
    const weGetElementInfo = function (filterArr) {
      let p = new Promise((resolve, reject) => {
        // console.log(server_url + uri)
        const query = wx.createSelectorQuery()
        filterArr.map(items => {
          if (items.type == 1) {
            return query.select(items.content).boundingClientRect()
          } else if (items.type == 2) {
            return query.selectAll(items.content).boundingClientRect()
          }
        })
        query.exec(result => {
          resolve(result)
        })
      })
      return p
    }
    const toTempPath = new Promise((resolve, reject) => {

      Promise.all([
        weGetElementInfo([{
          content: '.headerCarte',
          type: 1
        },
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainLeft .avatar',
          type: 1
        }, //用户形像照
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainLeft .avatarMask',
          type: 1
        }, //头像遮罩
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainRight .companyInfo .company',
          type: 1
        }, //公司名称
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainRight .companyInfo .logo',
          type: 1
        }, //公司logo
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainRight .positionInfo2 .job',
          type: 1
        }, //职位
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainRight .positionInfo2 .point',
          type: 1
        }, //点
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainRight .positionInfo .name',
          type: 1
        }, //名字
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainRight .phoneInfo .phone',
          type: 1
        }, //电话
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainRight .phoneInfo .icon',
          type: 1
        }, //电话Icon
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainRight .mailInfo .mail',
          type: 1
        }, //邮箱
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainRight .mailInfo .icon',
          type: 1
        }, //邮箱Icon
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainRight .addrInfo .addr',
          type: 1
        }, //地址
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .mainContent .mainRight .addrInfo .icon',
          type: 1
        }, //地址Icon
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .body_welcome .body_welcome_1',
          type: 1
        }, //描述内容1
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .body_welcome .body_welcome_2',
          type: 1
        }, //描述内容2
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .body_welcome .body_welcome_3',
          type: 1
        }, //描述内容3
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .body_welcome .body_welcome_4',
          type: 1
        }, //描述内容4
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .body_qrcode .qrcode_main .qrcode_main_img',
          type: 1
        }, //小程序码
        {
          content: '.headerCarte .headerCarte_main .carte_mainBox .body_qrcode .qrcode_tip .qrcode_tip_content',
          type: 1
        }, //长按识别字

        ]),

        wxGetImageInfo(params.img.src.split('?x-oss-process=style/poster_image')[0] + '?x-oss-process=style/index_mp'),
        wxGetImageInfo(params.comLogo.src),
        wxGetImageInfo(that.data.qrcodeUrl),
        wxGetImageInfo(that.data.bannerUrl),

      ]).then(res => {
        console.log(res);
        //海报距离名片顶部的距离
        let topBorder = res[0][0].top
        //海报距离名片底部的距离
        let leftBorder = res[0][0].left
        //获取画布的宽
        let canvasWidth = res[0][0].width
        //获取画布的高
        let canvasHeight = parseFloat(res[0][0].height) + 200
        // let canvasHeight = 1300

        //创建画布上下文对象
        const ctx = wx.createCanvasContext('carte_canvas')
        var that = this
        // 个人形象照
        var height1 = that.data.imageheight1
        ctx.drawImage(res[1].path, 0, 0, 600, 630)
        // 白色背景
        // ctx.rect(0, 620, 630, 600)
        // ctx.setFillStyle('white')
        // ctx.fill()
        this.roundRect(ctx, 0, 620, 630, 600, 12, '#fff')

        // roundRect(ctx,0,0,canvasWidth,canvasHeight,10)



        // 形象照遮挡
        // ctx.drawImage('../../images/img_connection_shade.png', 358, 43, 36, 322)



        // 公司LOGO
        ctx.drawImage(res[2].path, 24, 578, 100, 100)
        ctx.save()

        // 名字
        ctx.setFontSize(35)
        ctx.font = 'bold'
        ctx.fillStyle = '#333'
        ctx.setTextBaseline('top')
        if (params.name.content.length > 3) {
          var name = params.name.content.substr(0, 3) + '..'
        } else {
          var name = params.name.content
        }
        ctx.fillText(name, 135, 639)
        ctx.save()

        // ctx.rect(50, 120, 185, 50)
        // ctx.setFillStyle('#F3F3F3')
        // ctx.fill()

        // 职位
        ctx.setFontSize(28)
        ctx.fillStyle = '#999'
        ctx.setTextBaseline('top')
        ctx.fillText(params.position.content, 288, 650)
        ctx.save()

        // 公司名称
        ctx.setFontSize(20)
        ctx.fillStyle = '#333'
        ctx.setTextAlign("left")
        ctx.setTextBaseline('top')
        ctx.fillText(params.comName.content, 55, 706)
        // 公司Icon
        ctx.drawImage('../../images/carteShow/ic_connectionshare_company.png', 24, 704, 22, 24)

        // 点
        // ctx.beginPath()
        // ctx.rect(568, 199, 7, 7)
        // ctx.setFillStyle('#333')
        // ctx.fill()



        // 电话
        ctx.setFontSize(20)
        ctx.fillStyle = '#333'
        ctx.fillText(params.mobile.content, 55, 760)

        // 电话Icon
        ctx.drawImage('../../images/carteShow/ic_connectionshare_phone.png', 24, 758, 22, 24)

        // 邮箱
        // ctx.setFontSize(17)
        // ctx.fillStyle = '#333'
        // ctx.fillText(params.email.content, 50, 264)

        // 邮箱Icon
        // ctx.drawImage('../../images/carteShow/email.png', 565, 266, 20, 16)

        // 地址
        ctx.setFontSize(20)
        ctx.fillStyle = '#333';
        // ctx.fillText(params.address.content, 584, 301, 250, 28)
        var str = params.address.content
        that.drawText(ctx, str, 55, 814, 28, 824);

        // 地址Icon
        ctx.drawImage('../../images/carteShow/ic_connectionshare_location.png', 24, 812, 22, 24)

        // 灰色
        ctx.setFillStyle('#F4F4F4')
        ctx.fillRect(24, 874, 385, 100)
        ctx.drawImage('../../images/carteShow/ic_connectionshare_arrow.png', 408, 910, 20, 20)


        // 描述内容3
        ctx.setFontSize(21)
        ctx.fillStyle = '#333';
        ctx.fillText('这是我的人脉信息', 38, 894)

        // 描述内容4
        ctx.setFontSize(20)
        ctx.fillStyle = '#666';
        ctx.fillText('请惠存～', 38, 930)

        // 小程序码
        ctx.drawImage(res[3].path, 440, 846, 140, 140)



        // // 描述内容1
        // ctx.setFontSize(20)
        // ctx.setTextAlign("left")
        // ctx.fillStyle = '#333';
        // ctx.fillText('您好,', 47, 403)

        // // 描述内容2
        // ctx.setFontSize(20)
        // ctx.fillStyle = '#333';
        // // ctx.fillText('我是' + params.comName.content + ' ' + params.position.content + ' ' + params.name.content, 47, 452)
        // var str1 = '我是' + params.comName.content + ' ' + params.position.content + ' ' + params.name.content
        // that.drawText(ctx, str1, 47, 452, 30, 260);

        // // 描述内容3
        // ctx.setFontSize(20)
        // ctx.fillStyle = '#333';
        // ctx.fillText('这是我的人脉信息, 请保存。', 47, 509)

        // // 描述内容4
        // ctx.setFontSize(20)
        // ctx.fillStyle = '#333';
        // ctx.fillText('谢谢', 47, 550)



        // // banner
        // // ctx.drawImage(res[4].path, 52, 638, 295, 122)

        // // 长按识别字
        // ctx.setFontSize(15)
        // ctx.fillStyle = '#999';
        // ctx.fillText('长按识别太阳码，收下人脉信息', 220, 770)

        ctx.draw(false, (canvas_res) => {
          // console.log(canvas_res)
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 600,
            height: 1000,
            canvasId: 'carte_canvas',
            success(canvas_temp_res) {
              // console.log(canvas_temp_res)
              wx.hideLoading();
              var tempFilePath = canvas_temp_res.tempFilePath;
              wx.saveImageToPhotosAlbum({
                filePath: tempFilePath,
                success(res) {
                  wx.showModal({
                    content: '图片已保存到相册，赶紧晒一下吧~',
                    showCancel: false,
                    confirmText: '好的',
                    confirmColor: '#333',
                    success: function (res) {
                      if (res.confirm) {
                        if (that.data.CarteInfo.id != app.globalData.userInfo.id) {
                          app.radarAdd(that.data.CarteInfo.id, 30, '', '', app.globalData.userInfo.logo)
                          app.addlog(that.data.CarteInfo.id, that.data.CarteInfo.name.content, app.globalData.userInfo.id, app.globalData.userInfo.username, app.globalData.userInfo.logo, 30, '')
                        }

                        that.setData({
                          hidden: true
                        })
                        resolve(canvas_temp_res.tempFilePath)
                      }
                    },
                    fail: function (res) {
                      resolve(canvas_temp_res.tempFilePath)
                    }
                  })
                },
                fail: function (res) {
                  wx.showToast({
                    title: res.errMsg,
                    icon: 'none',
                    duration: 2000
                  })
                }
              })
            },
            fail(canvas_temp_err) {
              reject(canvas_temp_err)
            }
          })

        })
      })
    })
    return toTempPath
  },

  roundRect(ctx, x, y, w, h, r, c = '#fff') {
    if (w < 2 * r) {
      r = w / 2;
    }
    if (h < 2 * r) {
      r = h / 2;
    }

    ctx.beginPath();
    ctx.fillStyle = c;

    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
    ctx.moveTo(x + r, y);
    ctx.lineTo(x + w - r, y);
    ctx.lineTo(x + w, y + r);

    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
    ctx.lineTo(x + w, y + h - r);
    ctx.lineTo(x + w - r, y + h);

    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
    ctx.lineTo(x + r, y + h);
    ctx.lineTo(x, y + h - r);

    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
    ctx.lineTo(x, y + r);
    ctx.lineTo(x + r, y);

    ctx.fill();
    ctx.closePath();
  },

  drawText: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
    let lineWidth = 0;
    let lastSubStrIndex = 0; //每次开始截取的字符串的索引
    for (let i = 0; i < str.length; i++) {
      lineWidth += ctx.measureText(str[i]).width;
      if (lineWidth > canvasWidth) {
        ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
        initHeight += 20; //22为 文字大小20 + 2
        lineWidth = 0;
        lastSubStrIndex = i;
        titleHeight += 22;
      }
      if (i == str.length - 1) { //绘制剩余部分
        ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
      }
    }
    // 标题border-bottom 线距顶部距离
    titleHeight = titleHeight + 10;
    return titleHeight;
  },

  getBanner() {
    var that = this;
    wx.request({
      url: baseUrl + '/platform_api/banners',
      method: 'POST',
      data: {
        position: 5
      },
      success: function (res) {
        that.setData({
          bannerUrl: res.data.data.img
        });
      },
      fail: function () { },
      complete: function (res) { }
    })
  },

  getQrcode() {
    var that = this;
    var getdata = app.globalData.userInfo.id + '-' + app.globalData.SwitchTabParams.v_id;

    wx.request({
      url: baseUrl + "/weixin_api/getWXACodeUnlimit", //域名省略
      data: {
        page: "pages/carteShow/carteShow",
        scene: getdata
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        const qrcodeUrl = res.data; //服务器小程序码地址
        that.setData({
          qrcodeUrl: qrcodeUrl
        })
      },
      fail: function () { },
      complete: function (res) { }

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getQrcode();
    this.getBanner();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})